package cn.sjx.org.service.impl;

import cn.sjx.basic.service.impl.BasicServiceImpl;
import cn.sjx.basic.utils.PageList;
import cn.sjx.org.domain.Department;
import cn.sjx.org.mapper.DepartmentMapper;
import cn.sjx.org.query.DepartmentQuery;
import cn.sjx.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;

//    @Override
//    public List<Department> getAll() {
//        return departmentMapper.getAll();
//    }
//
//    @Override
//    public Department getById(Serializable id) {
//
//        return departmentMapper.getById(id);
//    }

    @Override
    public void insert(Department department) {
        department.setCreateTime(new Date());
        departmentMapper.insert(department);
        String path = "";
        //新增部门时要设置它的path，要在添加结束后才来设置，因为这样才能得到mapper返回的id值
        if (Objects.isNull(department.getParent())) {
            path = path + "/"+ department.getId();
        } else {
            Long parentId = department.getParent().getId();
            path = path + departmentMapper.getById(parentId).getPath();
            path = path + "/" + department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Override
    public void update(Department department) {
        department.setUpdateTime(new Date());
        departmentMapper.update(department);
    }

    @Override
    public void deleteById(Serializable id) {
        departmentMapper.deleteById(id);

    }

    @Override
    public PageList<Department> pageList(DepartmentQuery query) {
        Long total = departmentMapper.loadTotal(query);
        if (total > 0) {
            List<Department> list = departmentMapper.loadData(query);
            return new PageList<>(total, list);
        }
        return new PageList<>();
    }

    @Override
    public void batchRemove(List<Long> ids) {
        if (ids == null || ids.size() == 0) {
            throw new RuntimeException("删除错误");
        }
        departmentMapper.batchRemove(ids);
    }


}
